<template>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
        <el-form label-width="80px" :inline="false" size="normal">
            <el-form-item label="SPU名称">
                <el-input v-model="fdata.spuName"></el-input>
            </el-form-item>

            <el-form-item label="SPU品牌">
                <el-select placeholder="请选择" clearable filterable v-model="fdata.tmId">
                    <el-option :label="val.tmName" :value="val.id" v-for="(val,index) in TrademarkList" :key="val.id">
                    </el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="SPU描述">
                <el-input type="textarea" v-model="fdata.description" />
            </el-form-item>

            <el-form-item label="SPU图片">
                <el-upload v-model:file-list="SpuImageList" action="/api/admin/product/fileUpload"
                    list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove">
                    <el-icon>
                        <Plus />
                    </el-icon>
                </el-upload>

            </el-form-item>


            <el-form-item label="销售属性">
                <el-select :placeholder="BaseSaleAttrList.length>0?`您还有${sel.length}未选择`:`没得选啦`" clearable filterable
                    v-model="shouJData">
                    <el-option :label="val.name" :value="`${val.id}:${val.name}`" v-for="(val,index) in sel"
                        :key="index"></el-option>
                </el-select>
                <el-button type="primary" size="default" :icon="Plus" @click="addAttribute" :disabled="shouJData == ''">
                    添加销售属性值</el-button>
            </el-form-item>

            <el-table border stripe style="margin:10px 0" :data="SpuSaleAttrList">
                <el-table-column label="序号" width="100px" type="index" align="center"></el-table-column>
                <el-table-column label="属性名" prop="saleAttrName"></el-table-column>
                <el-table-column label="属性值名称列表">
                    <template #="{row,$index}">
                        <el-tag v-for="(val,index) in row.spuSaleAttrValueList" :key="val.id" class="mx-1" closable
                            @close="handleClose(row.spuSaleAttrValueList,index)" style="margin:2px 5px">
                            {{ val.saleAttrValueName }}
                        </el-tag>
                        <el-input ref="inp" v-if="row.flag" v-model="row.inputValue" placeholder="请输入" size="normal"
                            clearable @blur="blurInput(row)" style="width:100px"></el-input>
                        <el-button type="primary" size="small" :icon="Plus" @click="PlusClick(row)" v-else></el-button>


                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template v-slot="{row,$index}">
                        <el-button type="danger" size="default" :icon="Delete" @click="hanbleDelete(row)"></el-button>

                    </template>
                </el-table-column>
            </el-table>

            <el-button type="primary" size="default" @click="save">保存</el-button>
            <el-button size="default" @click="qxBtn">取消</el-button>


        </el-form>
    </el-card>

</template>

<script setup lang="ts">
import { ref, computed, nextTick } from 'vue'
import { Plus, Delete } from '@element-plus/icons-vue'
import { reqTrademarkList, reqBaseSaleAttrList, reqSpuImageList, reqSpuSaleAttrList, reqAddOrUpdataList } from '@/api/product/spu/spu'
import type { UploadProps, UploadUserFile } from 'element-plus'
import { ElMessage } from "element-plus";

let TrademarkList = ref([])
let BaseSaleAttrList = ref([])
let SpuImageList = ref([])
let SpuSaleAttrList = ref([])
let shouJData = ref('')

let fdata = ref({})
//高亮的ref
let inp = ref()
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const blurInput = (row) => {
    row.flag = false
    if (row.inputValue.trim() == '') {
        ElMessage({
            type: 'error',
            message: '不能为空'
        })
        return;
    }

    let result = row.spuSaleAttrValueList.find(item => {
        return item.saleAttrValueName == row.inputValue
    })
    if (result) {
        ElMessage({
            type: 'error',
            message: '数据重复'
        })
        row.inputValue = ''
        return;
    }

    row.spuSaleAttrValueList.push({
        baseSaleAttrId: row.baseSaleAttrId,
        saleAttrValueName: row.inputValue
    })
}
const PlusClick = (row) => {
    row.flag = true
    row.inputValue = ''
    nextTick(() => {
        inp.value.focus()
    })


}
const qxBtn = () => {
    fdata.value = {}
    emit('figure', {
        soene: 0,
        flag: fdata.id ? 'updata' : 'add'
    })
}

let getSpuDataAdd = async (c3ID) => {
    fdata.value.category3Id = c3ID
    let tr = reqTrademarkList()
    let bs = reqBaseSaleAttrList()
    let result = await Promise.all([tr, bs]);
    TrademarkList.value = result[0]
    BaseSaleAttrList.value = result[1]

}


//保存按钮的回调
const save = async () => {

    fdata.value.spuImageList = SpuImageList.value.map((item) => {
        return {
            imgName: item.name,
            imgUrl: (item.response && item.response.data) || item.url,
        };
    });

    fdata.value.spuSaleAttrList = SpuSaleAttrList.value



    try {
        await reqAddOrUpdataList(fdata.value)
        ElMessage({
            type: 'success',
            message: '操作成功'
        })
        emit('figure', {
            soene: 0,
            flag: fdata.value.id ? 'updata' : 'add'
        })
    } catch (error) {
        ElMessage({
            type: 'error',
            message: '操作失败'
        })
    }

    fdata.value = {}

}

//计算属性
let sel = computed(() => {
    return BaseSaleAttrList.value.filter(item => {
        return SpuSaleAttrList.value.every(item1 => {
            return item.name != item1.saleAttrName
        })
    })
})
//添加属性的按钮回调
const addAttribute = () => {
    let [baseSaleAttrId, saleAttrName] = shouJData.value.split(":")
    SpuSaleAttrList.value.push({
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList: []
    })
    shouJData.value = ''
}

//属性值  删除的操作
const handleClose = (val, num: number) => {
    val.splice(num, 1)
}
//删除属性的操作
const hanbleDelete = (row) => {
    SpuSaleAttrList.value.splice(row, 1)
}

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    SpuImageList.value = uploadFiles
    console.log(SpuImageList.value)
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}

let emit = defineEmits(['figure'])

//获取数据的回调 子组件定义 在父组件调用触发
let getSpuDataList = async (spu) => {
    let ps1 = reqTrademarkList()
    let ps2 = reqBaseSaleAttrList()
    let ps3 = reqSpuImageList(spu.id)
    let ps4 = reqSpuSaleAttrList(spu.id)

    fdata.value = spu

    let result = await Promise.all([ps1, ps2, ps3, ps4])

    TrademarkList.value = result[0]
    BaseSaleAttrList.value = result[1]
    SpuImageList.value = result[2].map(item => {
        return {
            name: item.imgName,
            url: item.imgUrl
        }
    })
    SpuSaleAttrList.value = result[3]
}



defineExpose({
    getSpuDataList, getSpuDataAdd
})
</script>

<style scoped>

</style>